﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;

namespace WinHBM.Core.Bluetooth
{

    public delegate void FoundDevice(BluetoothManager manager, BluetoothDeviceInfo device);
    public delegate void DiscoveryCompleted();

    public class BluetoothManager
    {

        private static readonly string DEVICE_ID = "BOLUTEK";
        public event FoundDevice FoundDevice;
        public event DiscoveryCompleted DiscoveryCompleted;


        public BluetoothClient Connect(String address)
        {
            BluetoothAddress addr = BluetoothAddress.Parse(address);
            return Connect(addr);
        }

        public BluetoothClient Connect(BluetoothAddress address)
        {
            BluetoothEndPoint ep = new BluetoothEndPoint(address, BluetoothService.SerialPort);
            BluetoothClient client = new BluetoothClient();
            client.Connect(ep);
            return client;
        }


        public void StartDiscovery()
        {
            BluetoothRadio BuleRadio = BluetoothRadio.PrimaryRadio;
            BuleRadio.Mode = RadioMode.Connectable;
            
            BluetoothComponent compoment = new BluetoothComponent();
            compoment.DiscoverDevicesComplete += Compoment_DiscoverDevicesComplete;
            compoment.DiscoverDevicesProgress += Compoment_DiscoverDevicesProgress;
            compoment.DiscoverDevicesAsync(5, false, false, false, true, null);
        }

        private void Compoment_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e)
        {
            
        }

        private void Compoment_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e)
        {
            BluetoothDeviceInfo[] Devices = e.Devices;
            foreach (BluetoothDeviceInfo deviceInfo in Devices)
            {
                if (!deviceInfo.DeviceName.Equals(DEVICE_ID))
                {
                    continue;
                }

                if (FoundDevice != null)
                {
                    FoundDevice(this, deviceInfo);
                }
            }

            if(DiscoveryCompleted != null)
            {
                DiscoveryCompleted();
            }
        }

    }
}
